package com.imooc.trading_system.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.imooc.trading_system.dto.LoginUserDto;
import com.imooc.trading_system.enums.BizCodeEnum;
import com.imooc.trading_system.utils.CommonUtils;
import com.imooc.trading_system.utils.JWTUtils;
import com.imooc.trading_system.utils.JsonData;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Feng zhaoxi
 * @date 2021/12/29 1:53 下午
 * @Description TODO
 */
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUserDto> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String accesToken = request.getHeader("token");
        if (accesToken == null) {
            accesToken = request.getParameter("token");
        }

        if (StringUtils.isNotBlank(accesToken)) {
            Claims claims = JWTUtils.checkJWT(accesToken);
            if (claims == null) {
                //告诉登录过期，重新登录
                CommonUtils.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT));
                return false;
            }
            long userId = Long.valueOf(claims.get("id").toString());
            String user = (String) claims.get("user");

            LoginUserDto loginUser = LoginUserDto
                    .builder()
                    .id(userId)
                    .user(user)
                    .build();
            threadLocal.set(loginUser);
            return true;
        }
        CommonUtils.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_NOT_LOGIN));
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
